export default {
  // 为当前模块开启命名空间
  namespaced: true,

  // 数据
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || "[]")
  }),
  // 方法
  mutations: {
    // 添加商品到购物车
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id);
      if (!findResult) {
        state.cart.push(goods);
      } else {
        findResult.goods_count++;
      }
      this.commit('m_cart/saveCart');
    },
    // 将cart存放到storage中
    saveCart(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 更新商品的勾选状态
    updataGoodsState(state, goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_state = goods.goods_state;
        this.commit('m_cart/saveCart');
      }
    },
    // 更新数量
    updataGoodsCount(state, goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_count = goods.goods_count;
        this.commit('m_cart/saveCart');
      }
    },
    // 在购物车中删除该商品
    deleteGoods(state,goods) {
      state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id);
      this.commit('m_cart/saveCart');
    },
    // 改变当前所有商品的状态
    changeAllGoodsState(state,newState) {
      state.cart.forEach(item => {
        item.goods_state = newState
      })
      this.commit('m_cart/saveCart')
    }
  },
  // 计算属性
  getters: {
    // 统计购物车中商品的总数量
    total(state) {
      let total = 0;
      state.cart.forEach(goods => {
        return total += goods.goods_count;
      })
      return total
    },
    // 统计已勾选商品数量的总数 已勾选商品数量相加 先筛选后汇总 =》filter -- reduce
    checkedCount(state) {
      return state.cart.filter(item => item.goods_state === true).reduce((req,x) => req += x.goods_count,0)
    },    
    // 统计已勾选商品的总价格,并保留两位小数
    totalCheckedPrice(state) {
      return state.cart.filter(item => item.goods_state).reduce((req,x) => req = req + (x.goods_count * x.goods_price),0).toFixed(2)
    }
  }
}
